<template>
	<el-input v-model="innerValue" :placeholder="placeholder">
		<template #suffix>
			<el-icon class="icon-button" @click="selectPath" :title="title">
				<Document v-if="props.type === 'file'" />
				<Folder v-else />
			</el-icon>
		</template>
	</el-input>
</template>

<script setup lang="ts">
import { ref, watch, PropType, computed } from 'vue';
import { API } from '@v/utils/API';
import { Folder, Document } from '@element-plus/icons-vue';
import { FileFilter } from 'electron';

const emits = defineEmits(['update:modelValue']);

const props = defineProps({
	modelValue: {
		type: String,
		default: '',
	},
	type: {
		type: String as PropType<'file' | 'dir' | 'save-path'>,
		default: 'file',
	},
	placeholder: String,
	tiele: String,
	defaultPath: String,
	multiple: Boolean,
	showHiddenFiles: Boolean,
	filters: Array as PropType<FileFilter[]>,
});

const innerValue = ref('');

// 选择路径
function selectPath() {
	if (props.type === 'save-path') {
		API.invoke('select-save-path', props.tiele, props.defaultPath, [{ name: 'markdown', extensions: ['md'] }]).then(
			(savePath) => {
				if (savePath) innerValue.value = savePath;
			}
		);
	} else if (props.type === 'dir') {
		API.invoke('select-dir', props.tiele, props.defaultPath, props.multiple, props.showHiddenFiles).then(
			(paths) => {
				if (paths) {
					innerValue.value = paths[0];
				}
			}
		);
	} else if (props.type === 'file') {
		API.invoke(
			'select-file',
			props.tiele,
			props.defaultPath,
			props.filters,
			props.multiple,
			props.showHiddenFiles
		).then((paths) => {
			if (paths) {
				innerValue.value = paths[0];
			}
		});
	}
}

watch(innerValue, (s) => {
	emits('update:modelValue', s);
});
watch(
	() => props.modelValue,
	(s) => {
		innerValue.value = s;
	},
	{ immediate: true }
);

const title = computed(() => {
	switch (props.type) {
		case 'file':
			return '选择文件';
		case 'dir':
			return '选择文件夹';
		case 'save-path':
			return '选择保存路径';
	}
});
</script>

<style scoped lang="scss"></style>
